package com.live.task;

import java.io.InputStream;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.live.activity.LiveVideoActivity;
import com.live.activity.R;
import com.live.adapter.LiveVideoSimpleAdapter;
import com.live.common.Constant;
import com.live.tools.LiveTools;

public class LiveVideo extends AsyncTask<Bundle, Integer, String> {
	private List<Map<String, Object>> liveVideoList = new ArrayList<Map<String, Object>>();

	private ListView videoList = null;

	private Context context = null;

	private String locale = LiveTools.getLocaleLanguage();

	private LinearLayout viewMatch = null;

	public LiveVideo(Context context, ListView videoList, LinearLayout viewMatch) {
		this.context = context;
		this.videoList = videoList;
		this.viewMatch = viewMatch;

	}

	ProgressDialog mProgressDialog = null;

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		Log.i("PageTask", "onPreExecute()  " + Thread.currentThread().getId());
	}

	@Override
	protected String doInBackground(Bundle... params) {

		Log.i("PageTask", "doInBackground... " + Thread.currentThread().getId());
		String matchTime = params[0].getString("matchTime").substring(0, 10);
		String homeTeam = params[0].getString("homeTeamName");
		String visitTeam = params[0].getString("visitTeamName");
		String url = Constant.SITE_URL + "live_video.php?locale=" + LiveTools.getLocaleLanguage();
		try {
			url += "&matchTime=" + matchTime + "&videoCategory=0";
			url += "&homeTeam=" + URLEncoder.encode(homeTeam, "UTF-8") + "&visitTeam="
					+ URLEncoder.encode(visitTeam, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		liveVideoList = getServerData(url);
		publishProgress(new Integer[0]);
		return null;
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		Log.i("PageTask", "onProgressUpdate()  " + Thread.currentThread().getId());

		LiveVideoSimpleAdapter adapter = new LiveVideoSimpleAdapter(context, liveVideoList, R.layout.video_list,
				new String[] { "videoTitle", "videoLength", "videoWatch", "videoTime" }, new int[] { R.id.videoTitle,
						R.id.videoLength, R.id.videoWatch, R.id.videoTime }, videoList);
		videoList.setAdapter(adapter);
		videoList.setOnItemClickListener(new OnItemClickListener() {

			// 从当前画面到比分明细画面跳转，并传值。
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

				Map<String, Object> video = liveVideoList.get(arg2);

				Intent intent = new Intent();

				intent.setClass(context, LiveVideoActivity.class);

				// 实例化 Bundle，设置需要传递的参数
				Bundle bundle = new Bundle();
				bundle.putString("videoId", video.get("videoId").toString());
				bundle.putString("videoUrl", video.get("videoUrl").toString());
				bundle.putString("videoTitle", video.get("videoTitle").toString());

				intent.putExtras(bundle);

				context.startActivity(intent);
			}
		});
	}

	@Override
	protected void onPostExecute(String result) {
		Log.i("PageTask", "onPostExecute()  " + Thread.currentThread().getId());

		LinearLayout loadData = (LinearLayout) viewMatch.findViewById(R.id.loadData);
		viewMatch.removeView(loadData);
	}

	public List<Map<String, Object>> getServerData(String url) {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		HttpClient client = new DefaultHttpClient();
		try {
			HttpGet request = new HttpGet(new URI(url));
			request.addHeader("Accept-Encoding", "gzip");
			HttpResponse response = client.execute(request);

			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();

				if (entity != null) {
					String out = null;
					InputStream is = entity.getContent();
					if (entity.getContentEncoding().getValue().contains("gzip")) {
						out = LiveTools.isToString(is);
					} else {
						out = EntityUtils.toString(entity);
					}
					try {
						String result = new JSONObject(out).getString("result");
						if (Constant.Y.equals(result)) {
							JSONArray video = new JSONObject(out).getJSONArray("results");
							for (int i = 0; i < video.length(); i++) {
								Map<String, Object> map = new HashMap<String, Object>();
								map.put("videoId", video.getJSONObject(i).get("videoId"));
								map.put("videoTitle", LiveTools.tradToSimp(video.getJSONObject(i).get("videoTitle")
										.toString(), locale));
								map.put("videoImgUrl", video.getJSONObject(i).get("videoImgUrl"));
								map.put("videoLength", video.getJSONObject(i).get("videoLength"));
								map.put("videoUrl", video.getJSONObject(i).get("videoUrl"));
								map.put("videoWatch", video.getJSONObject(i).get("videoWatch"));
								map.put("videoTime", video.getJSONObject(i).get("updateDate"));
								data.add(map);
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			Toast.makeText(context, "远程服务器无响应，请稍候再试！", Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
		return data;
	}
}